
// const db = require('../db/index')
// 导入数据库操作模块
const db = require("../db")
// 导入处理路径的 path 核心模块
const path = require('path')
const { param } = require("express/lib/request")

// 获取文章分类列表的处理函数
exports.getArticleCates = (req, res) => {
    const sqlstr = 'select * from ev_article_cate where is_delete=0 order by id asc'
    db.query(sqlstr, (err, results) => {
        if (err) return res.send(err)
        if (results.lengtn == 0) return res.send('查找失败,文章不存在')
        res.send({
            status: 0,
            message: '获取文章分类列表成功',
            data: results
        })
    })
    // res.send('请求文章数据成功')
}
// 新增文章分类的处理函数
exports.addcates = (req, res) => {
    const sqlstr = `select * from ev_article_cate where name=? or alias=?`
    db.query(sqlstr, [req.body.name, req.body.alias], (err, results) => {
        if (err) return res.cc(err)
        if (results.length === 2) return res.cc('分类名称与别名被占用，请重新输入')
        if (results.length === 1 && results[0].name === req.body.name && results[0].alias === req.body.alias) return res.cc('分类名称与别名被占用，请重新输入')
        if (results.length === 1 && results[0].name === req.body.name) return res.cc('分类名称被占用')
        if (results.length === 1 && results[0].alias === req.body.alias) return res.cc('分类别名被占用')
        // res.cc('未被占用，请写入数据库',0)
        // INSERT into ev_users(username,password) values(?,?)
        const sql = 'INSERT into ev_article_cate(name,alias) values(?,?)'
        db.query(sql, [req.body.name, req.body.alias], (err, results) => {
            if (err) res.cc(err)
            if (results.affectedRows !== 1) return res.cc('新增文章分类失败')
            res.cc('新增文章分类成功', 0)
        })
    })
    // res.send('新增文章分类成功')
}

// 删除文章类型的处理函数(根据ID)
exports.delecates = (req, res) => {
    // 查询要删除的文章分类是否存在
    const sqlstr = 'select * from ev_article_cate where id = ?'
    console.log('删除文章分类的数据', req.query);
    db.query(sqlstr, req.query.id, (err, results) => {
        if (err) return res.cc(err)
        console.log('results数据', results);
        if (results == 0) return res.cc('删除的文章类型不存在')
        // res.cc('可以删除',0)
        // update ev_users set user_pic=? where id = ?
        const sql = 'update ev_article_cate set is_delete=? where id = ? '
        db.query(sql, [1, req.query.id], (err, results) => {
            if (err) res.cc(err)
            if (results.affectedRows !== 1) return res.cc('删除文章类型失败')
            res.cc('删除文章类型成功', 0)
        })
    })
}

// 根据id获取文章分类的处理函数
exports.getArtCateById = (req, res) => {
    const sqlstr = 'select * from ev_article_cate where id = ?'
    db.query(sqlstr, req.params.id, (err, results) => {
        if (err) return res.cc(err)
        console.log(req.params.id);
        if (results.affectedRows) return res.cc('获取文章分类数据失败')
        res.send({
            status: 0,
            message: '获取文章分类列表成功',
            data: results[0]
        })
    })
}
// 根据id修改文章分类的处理函数
exports.updateArtCateById = (req, res) => {
    const sqlstr = 'select * from ev_article_cate where id = ?'
    db.query(sqlstr, req.body.id, (err, results) => {
        if (err) return res.cc('文章分类不存在')
        console.log(req.body.id);
        const sql = 'update ev_article_cate set ? where id =?'
        db.query(sql, [req.body, req.body.id], (err, results) => {
            // 执行SQL语句失败
            if (err) return res.cc(err)
            // 执行sql语句成功，但是影响的行数不等于1
            if (results.affectedRows !== 1) return res.cc('更新分类失败')
            res.cc('更新分类成功', 0)
        })
    })
}
// 发布新文章
exports.addArticle = (req, res) => {
    // res.send('添加文章成功')
    console.log(req.file);
    console.log('----------------');
    console.log('body', req.body);
    // 手动判断是否上传了文章封面
    if (!req.file || req.file.fieldname !== 'cover_img') return res.cc('文章封面是必选参数！')
    // 表单数据合法，继续后面的处理流程...
    const articleInfo = {
        // 标题、内容、状态、所属的分类Id
        ...req.body,
        // 文章封面在服务器端的存放路径
        cover_img: path.join('/uploads', req.file.filename),
        // 文章发布时间
        pub_date: new Date(),
        // 文章作者的Id
        author_id: req.user.id,
    }
    const sqlstr = 'insert into ev_articles set ?'
    db.query(sqlstr, articleInfo, (err, results) => {
        if (err) return res.cc(err)
        if (results.affectedRows !== 1) return res.cc('新增文章失败')
        // 发布文章成功
        res.cc('新增文章成功', 0)
    })
}

// 获取文章列表的处理函数
exports.getArticleList = (req, res) => {
    // SELECT * FROM ev_articles LIMIT ?; 
    if (req.query.state || req.query.id) {
        let sqlstr;
        if (req.query.state && req.query.id) {
            sqlstr = `select * from ev_articles where is_delete=0 and state = ? and cate_id = ?`
        } else {
            // select * from ev_articles where is_delete=1 and state = '' or cate_id = 6
            sqlstr = `select * from ev_articles where is_delete = 0 and (state = ? or cate_id = ?)`
        }
        // select * FROM ev_articles  limit ${(req.query.pagenum - 1) * req.query.pagesize},${req.query.pagesize}
        console.log(req.query);
        db.query(sqlstr, [req.query.state, req.query.id], (err, results) => {
            if (err) return res.cc(err)
            const total = results.length
            let sql;
            if (req.query.state && req.query.id) {
                sql = `select ev_articles.*,ev_article_cate.name,ev_article_cate.alias  FROM ev_articles LEFT JOIN ev_article_cate on cate_id=ev_article_cate.id where ev_articles.is_delete=0 and state = ? and cate_id = ? limit ${(req.query.pagenum - 1) * req.query.pagesize},${req.query.pagesize}`
            } else {
                sql = `select ev_articles.*,ev_article_cate.name,ev_article_cate.alias  FROM ev_articles LEFT JOIN ev_article_cate on cate_id=ev_article_cate.id where ev_articles.is_delete=0 and (state = ? or cate_id = ?) limit ${(req.query.pagenum - 1) * req.query.pagesize},${req.query.pagesize}`
            }
            db.query(sql, [req.query.state, req.query.id], (err, results) => {
                res.send({
                    status: 0,
                    message: '获取文章列表成功',
                    data: results,
                    total: total
                })
            })
            // if((req.query.pagenum * req.query.pagesize) > results.length) {
            //     req.query.pagesize = 0
            // }
            // const data = results.slice((req.query.pagenum - 1) * req.query.pagesize,req.query.pagesize)
        })
    } else {
        // 左外连接 连接两个表，方便返回作者和分类名称
        const sqlstr = 'select ev_articles.*,ev_article_cate.name,ev_article_cate.alias  FROM ev_articles LEFT JOIN ev_article_cate on cate_id=ev_article_cate.id where ev_articles.is_delete=0'
        db.query(sqlstr, (err, results) => {
            if (err) return res.cc(err)
            const total = results.length
            console.log(req.query);
            // 分页
            const sql = `select ev_articles.*,ev_article_cate.name,ev_article_cate.alias  FROM ev_articles LEFT JOIN ev_article_cate on cate_id=ev_article_cate.id where ev_articles.is_delete=0 limit ${(req.query.pagenum - 1) * req.query.pagesize},${req.query.pagesize}`
            db.query(sql, (err, results) => {
                if (err) return res.cc(err)
                res.send({
                    status: 0,
                    message: '获取文章列表成功',
                    data: results,
                    total: total
                })
            })
        })
    }

}
// 根据id获取文章详情的处理函数
exports.getArticleInfo = (req, res) => {
    const sqlstr = 'select * from ev_articles where id = ?'
    db.query(sqlstr, req.query.id, (err, results) => {
        if (err) return res.cc(err)
        // 把第一次查找的结果保存在data中，方便在后面的查询里使用
        let data = results[0]
        const author = 'select * from ev_users where id = ?'
        db.query(author, data.author_id, (err, results) => {
            // 根据第一次查询结果，查询文章作者
            if (err) return res.cc(err)
            // console.log('作者',results);
            data.username = results[0].username
            data.nickname = results[0].nickname
            const cate = 'select * from ev_article_cate where id = ?'
            db.query(cate, data.cate_id, (err, results) => {
                // 根据第一次查询结果，查询文章类别
                if (err) return res.cc(err)
                data.cate_name = results[0].name
                console.log(data);
                res.send({
                    status: 0,
                    message: '获取文章详情成功',
                    data: data
                })
            })
        })
    })
}
// 删除文章数据的处理函数(根据ID) 假删除，把文章的is_delete设为1
exports.deleArticle = (req, res) => {
    // 查询要删除的文章是否存在
    const sqlstr = 'select * from ev_articles where id = ?'
    console.log('删除文章的数据', req.query);
    db.query(sqlstr, req.query.id, (err, results) => {
        if (err) return res.cc(err)
        console.log('删除文章的results数据', results);
        if (results == 0) return res.cc('删除的文章不存在')
        // res.cc('可以删除',0)
        // update ev_users set user_pic=? where id = ?
        const sql = 'update ev_articles set is_delete=? where id = ? '
        db.query(sql, [1, req.query.id], (err, results) => {
            if (err) res.cc(err)
            if (results.affectedRows !== 1) return res.cc('删除文章失败')
            res.cc('删除文章成功', 0)
        })
    })
}
// 以下新增
// 根据职位类别（name）查职位的ID
exports.searchArticleInfo = (req, res) => {
    const sqlstr = 'select * from ev_article_cate where name = ?'
    db.query(sqlstr, req.query.name, (err, results) => {
		console.log(results);
        if (err) return res.cc('职位不存在')
		if (results.length == 0) return res.cc('查找失败,职位不存在')
        res.send({
            status: 0,
            message: '根据职位类别获取文章分类ID成功',
            data: results[0]
        })
    })
}
// 根据职位ID查职位列表
exports.searchArticleInfoById = (req, res) => {
    const sqlstr = 'select * from ev_articles where cate_id = ? and is_delete=0'
    db.query(sqlstr, req.query.id, (err, results) => {
		console.log(results);
        if (err) return res.cc('职位不存在')
		if (results.length == 0) return res.cc('查找失败,职位不存在')
        res.send({
            status: 0,
            message: '根据职位类别获取文章分类ID成功',
            data: results
        })
    })
}